import { Component, OnInit, ViewContainerRef, ViewChild, TemplateRef, AfterViewInit, Input, EventEmitter, Output, SimpleChanges, ComponentRef, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';
import { OverlayConfig, Overlay, OverlayRef, GlobalPositionStrategy } from '@angular/cdk/overlay';
import { ComponentPortal, TemplatePortalDirective } from '@angular/cdk/portal';
import { InputBoolean } from 'ng-zorro-antd';
import { isNullOrUndefined } from 'util';
// import { ModalComponent } from './modal/modal.component';

@Component({
  selector: 'app-zzj-modal',
  templateUrl: './zzj-modal.component.html',
  styleUrls: ['./zzj-modal.component.less']
})
export class ZzjModalComponent<T = any, R = any> implements AfterViewInit {
  @Input() public zzVisible = false;
  @Input() public zzTitle: string | TemplateRef<{}>; // 标题 | header模板
  @Input() public zzContent: TemplateRef<void>; // content模板
  @Input() public zzFooter: TemplateRef<void>;  // footer模板
  @Input() public zzRemovable = false;  // 是否可移动的弹框
  @Input() public zzMaskClosable = false;   // 是否点击背景板关闭
  @Input() public zzClassName: string;  // 弹框最外层class
  @Input() public zzTop: number;  // top距离
  @Input() public zzLeft: number; // left距离
  @Input() public zzBottom: number; // bottomjuli
  @Input() public zzRight: number;  // right距离
  @Input() public zzWidth: number | string; // modal宽度
  @Input() public zzHeight: number | string;  // modal高度
  // @Input() public zzClassName: string;  // 弹框最外层class
  @Output() public readonly zzAfterOpen = new EventEmitter<void>();
  @Output() public readonly zzAfterClose = new EventEmitter<void>();
  @Output() public readonly zzOnCancel = new EventEmitter<void>();  // 关闭事件
  @Output() public readonly zzOnOk = new EventEmitter<void>();  // 关闭事件
  @Output() public readonly zzKeyboard = new EventEmitter<number>();  // 键盘事件，监听keycode
  @ViewChild('overlayGlobalTemplate', { static: false }) public templateGlobalPortals: TemplatePortalDirective;
  @ViewChild('zzModalComponent', { static: false }) public zzModalComponent: any;
  public overlayRef: OverlayRef;
  public chatStyleModel: any = {

  };
  public get chatStyle() {
    return {
      width: this.chatStyleModel.width + 'px',
      height: this.chatStyleModel.height + 'px',
      left: this.chatStyleModel.left + 'px',
      top: this.chatStyleModel.top + 'px'
    };
  }
  public constructor(public overlay: Overlay) {
  }

  public ngAfterViewInit() {

  }

  public ngOnInit(): void {
  }

  public ngOnChanges(changes: SimpleChanges): void {

    if (changes.zzVisible) {
      this.handleVisibleStateChange(this.zzVisible, !changes.zzVisible.firstChange);
    }
  }

  private handleVisibleStateChange(visible: boolean, animation = true) {
    if (visible) {

      this.showOverlayGlobalPanelCenter();
      this.zzAfterOpen.emit();
    } else if (this.overlayRef) {
      this.overlayRef.dispose();
      this.zzAfterClose.emit();
    }
  }

  public closeModal() {
    this.zzOnCancel.emit();
  }

  public clickOnOk() {
    this.zzOnOk.emit();
  }

  public clickOnCancel() {
    this.zzOnCancel.emit();
  }

  public isNonEmptyString(value: {}): boolean {
    return typeof value === 'string' && value !== '';
  }

  public isTemplateRef(value: {}): boolean {
    return value instanceof TemplateRef;
  }

  public adjustPanel(event: any, styleModel: any, action: string) {
    if (!this.zzRemovable) {
      return;
    }
    event = event || window.event;
    if (event == null) {
      return;
    }
    event.stopPropagation();
    let preX = event.x;
    let preY = event.y;
    document.onmousemove = (evtMove: any) => {
      evtMove = evtMove || window.event;
      if (evtMove == null) {
        return;
      }
      let moveX = evtMove.x - preX;
      let moveY = evtMove.y - preY;

      if (action == "move") {
        styleModel.left = styleModel.left + moveX;
        styleModel.top = styleModel.top + moveY;
      }
      if (action == "resize-n") {
        styleModel.top = styleModel.top + moveY;
        styleModel.height = styleModel.height - moveY;
      }
      if (action == "resize-s") {
        styleModel.height = styleModel.height + moveY;
      }
      if (action == "resize-e") {
        styleModel.width = styleModel.width + moveX;
      }
      if (action == "resize-w") {
        styleModel.left = styleModel.left + moveX;
        styleModel.width = styleModel.width - moveX;
      }


      preX = evtMove.x;
      preY = evtMove.y;
    };
    document.onmouseup = (evtUp: any) => {
      document.onmousemove = null;
      document.onmouseup = null;
      preX = 0;
      preY = 0;
    };
  }


  /**
   * overlay 在整个屏幕的中间显示
   */
  public showOverlayGlobalPanelCenter() {
    // console.log(this.templateGlobalPortals);
    if (!this.templateGlobalPortals) {
      return;
    }
    // config: OverlayConfig overlay的配置，配置显示位置，和滑动策略
    const config = new OverlayConfig();
    // config.positionStrategy = this.overlay.position().global()
    let postion: GlobalPositionStrategy = this.overlay.position().global();
    if (!isNullOrUndefined(this.zzLeft)) {
      postion.left(this.zzLeft + 'px')
    } else {
      postion.centerHorizontally()
    }

    if (!isNullOrUndefined(this.zzBottom)) {
      console.log(this.zzBottom)
      postion.bottom(this.zzBottom + 'px')
    }
    if (!isNullOrUndefined(this.zzTop)) {
      postion.top(this.zzTop + 'px')
    } else {
      postion.top(`150px`);
    }
    if (!isNullOrUndefined(this.zzRight)) {
      postion.right(this.zzRight + 'px')
    }
    if (!isNullOrUndefined(this.zzWidth)) {
      if (typeof this.zzWidth == 'number') {
        postion.width(this.zzWidth + 'px')
      } else {
        postion.width(this.zzWidth)
      }
    }
    if (!isNullOrUndefined(this.zzHeight)) {
      if (typeof this.zzHeight == 'number') {
        postion.height(this.zzHeight + 'px')
      } else {
        postion.height(this.zzHeight)
      }
    }
    // 水平居中
    // .centerVertically('-100'); // 垂直居中
    // .left(`${this.globalOverlayPosition}px`) // 自己控制位置
    config.positionStrategy = postion;
    config.hasBackdrop = true; // 设置overlay后面有一层背景, 当然你也可以设置backdropClass 来设置这层背景的class
    config.backdropClass = "backdrop";
    this.overlayRef = this.overlay.create(config); // OverlayRef, overlay层

    this.overlayRef.backdropClick().subscribe(() => {
      // 点击了backdrop背景
      if (this.zzMaskClosable) {
        console.log('click backdrop');
        this.zzOnCancel.emit();
      }
    });
    // OverlayPanelComponent是动态组件
    // 创建一个ComponentPortal，attach到OverlayRef，这个时候我们这个overlay层就显示出来了。
    // overlayRef.attach(new ComponentPortal(ModalComponent, this.vcRef));
    this.overlayRef.attach(this.templateGlobalPortals);
    console.log(this.overlayRef);
    this.chatStyleModel.left = this.overlayRef.overlayElement.offsetLeft;
    this.chatStyleModel.top = this.overlayRef.overlayElement.offsetTop;
    // 监听overlayRef上的键盘按键事件
    this.overlayRef.keydownEvents().subscribe((event: KeyboardEvent) => {
      this.zzKeyboard.emit(event.keyCode);
    });
  }
}
